package com.finger.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.finger.common.constant.AuthConstant;
import com.finger.common.exception.BizCodeEnume;
import com.finger.common.utils.R;
import com.finger.common.vo.MemberVo;
import com.finger.gulimall.auth.feign.MemberRemoteService;
import com.finger.gulimall.auth.vo.LoginVo;
import com.finger.gulimall.auth.vo.MemberRespVo;
import com.finger.gulimall.auth.vo.RegistVo;
import lombok.extern.java.Log;
import lombok.extern.log4j.Log4j;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Log4j2
@Controller
public class LoginController {

    @Autowired
    private MemberRemoteService memberRemoteService;

    @PostMapping("regist")
    public String regist(@Valid RegistVo registVo,
                         BindingResult result,
                         RedirectAttributes redirectAttributes
    ) {

        if (result.hasErrors()) {
            // 请求参数有问题直接返回到登录页并带上错误信息
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        R register = memberRemoteService.register(registVo);

        if (register.getCode() == 15001) {
            // 账号被占用
            HashMap<String, Object> map = new HashMap<>();
            map.put("username", "用户名被占用");
            redirectAttributes.addFlashAttribute("errors", map);
            return "redirect:http://auth.gulimall.com/reg.html";
        } else if (register.getCode() == 15002) {
            // 手机号已使用
            HashMap<String, Object> map = new HashMap<>();
            map.put("phone", "手机号被占用");
            redirectAttributes.addFlashAttribute("errors", map);
            return "redirect:http://auth.gulimall.com/reg.html";
        } else if (register.getCode() == 0) {
            // 注册成功,跳登录页
            return "redirect:http://auth.gulimall.com/login.html";
        }
        // 未知异常
        return "redirect:http://auth.gulimall.com/reg.html";
    }

    @PostMapping("/login")
    public String doLogin(@Valid LoginVo loginVo,
                        BindingResult result,
                        RedirectAttributes redirectAttributes,
                        HttpSession session,
                          @RequestParam(value = "url",required = false) String url) {

        if (result.hasErrors()) {
            // 参数校验错误
            Map<String, String> map = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors", map);
            return "redirect:http://auth.gulimall.com/login.html";
        }

        R success = memberRemoteService.login(loginVo);
        if (success.getCode() == BizCodeEnume.MEMBER_LOGINACCT_SUCCESS.getCode()) {
            // 登录成功,从响应体中取出数据，
            String member = (String) success.get(AuthConstant.LOGIN_MEMBER);

            log.info(member);
            MemberVo loginMember = JSON.parseObject(member, new TypeReference<MemberVo>(){});
            session.setAttribute(AuthConstant.LOGIN_MEMBER, loginMember);
//            if(!StringUtils.isEmpty(url)){
//                return "redirect:"+url;
//            }
            return "redirect:http://gulimall.com";
        } else if (success.getCode() == BizCodeEnume.MEMBER_LOGINACCT_FAILD.getCode()) {
            // 账号或密码错误
            redirectAttributes.addFlashAttribute("errors", success);
            redirectAttributes.addFlashAttribute("redirect_url",url);
            return "redirect:http://auth.gulimall.com/login.html";
        } else {
            // 未知异常
            redirectAttributes.addFlashAttribute("errors",success);
            redirectAttributes.addFlashAttribute("redirect_url",url);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }

    @GetMapping("/login.html")
    public String login(@RequestParam(value = "redirect_url",required = false)String url,
                        Model model,
                        HttpSession session) {
        // 如果session域中有这个对象，直接返回
        Object loginMember = session.getAttribute(AuthConstant.LOGIN_MEMBER);

        if(loginMember!=null){
            return "redirect:http://gulimall.com";
        }

        if(!StringUtils.isEmpty(url)){
            // 添加登录成功后回调地址
            model.addAttribute("url",url);
        }

        return "login";
    }
}
